
import React, { useState, useEffect } from 'react';
import { Card, Descriptions, Button, Tag, Space, message, Spin } from 'antd';
import { ArrowLeftOutlined, EditOutlined, BookOutlined, EuroOutlined } from '@ant-design/icons';
import { history, useParams } from '@umijs/max';
import { getBookDetail } from '@/services/bookAPi';
import { getBorrowings } from '@/services/BorrowingAPI';
import type { BookItem } from '@/types/book';

const BookDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const [book, setBook] = useState<BookItem | null>(null);
  const [loading, setLoading] = useState(false);
  const [borrowing, setBorrowing] = useState<any>(null);

  // 获取图书详情
  const fetchBookDetail = async () => {
    if (!id) return;

    setLoading(true);
    try {
      const res = await getBookDetail(Number(id));
      setBook(res.data);
    } catch (error) {
      message.error('获取图书详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取借阅信息
  const fetchBorrowing = async () => {
    if (!id) return;

    try {
      const res = await getBorrowings({ book_id: id, limit: 1 });
      if (res.data.results.length > 0) {
        setBorrowing(res.data.results[0]);
      }
    } catch (error) {
      // 没有借阅记录是正常情况，不需要显示错误
    }
  };

  useEffect(() => {
    fetchBookDetail();
    fetchBorrowing();
  }, [id]);

  // 编辑图书
  const handleEdit = () => {
    history.push(`/books/edit/${id}`);
  };

  // 借阅图书
  const handleBorrow = async () => {
    if (!id) return;

    try {
      await BorrowingAPI.createBorrowing({ book: Number(id) });
      message.success('借阅成功');
      fetchBorrowing(); // 刷新借阅信息
    } catch (error) {
      message.error('借阅失败');
    }
  };

  // 归还图书
  const handleReturn = async () => {
    if (!id || !borrowing) return;

    try {
      await BorrowingAPI.returnBook(Number(id));
      message.success('归还成功');
      fetchBorrowing(); // 刷新借阅信息
    } catch (error) {
      message.error('归还失败');
    }
  };

  // 状态标签
  const renderStatusTag = (status: string) => {
    const statusMap = {
      available: { color: 'green', text: '可借阅' },
      borrowed: { color: 'orange', text: '已借出' },
      reserved: { color: 'blue', text: '已预约' },
      damaged: { color: 'red', text: '损坏' },
      lost: { color: 'purple', text: '丢失' },
    };
    const statusInfo = statusMap[status as keyof typeof statusMap] || { color: 'default', text: status };
    return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
  };

  if (loading) {
    return <div style={{ padding: 24, textAlign: 'center' }}><Spin size="large" /></div>;
  }

  if (!book) {
    return <div>图书不存在</div>;
  }

  return (
    <div>
      <Card style={{ marginBottom: 16 }}>
        <Space>
          <Button 
            icon={<ArrowLeftOutlined />} 
            onClick={() => history.push('/books/list')}
          >
            返回列表
          </Button>
          <Button 
            type="primary" 
            icon={<EditOutlined />} 
            onClick={handleEdit}
          >
            编辑图书
          </Button>
          {book.status === 'available' && (
            <Button 
              type="primary" 
              icon={<BookOutlined />} 
              onClick={handleBorrow}
            >
              借阅图书
            </Button>
          )}
          {book.status === 'borrowed' && borrowing && (
            <Button 
              type="primary" 
              icon={<EuroOutlined />} 
              onClick={handleReturn}
            >
              归还图书
            </Button>
          )}
        </Space>
      </Card>

      <Card title="图书详情">
        <Descriptions bordered column={2}>
          <Descriptions.Item label="书名">{book.title}</Descriptions.Item>
          <Descriptions.Item label="状态">
            {renderStatusTag(book.status)}
          </Descriptions.Item>
          <Descriptions.Item label="作者">{book.author}</Descriptions.Item>
          <Descriptions.Item label="ISBN">{book.isbn}</Descriptions.Item>
          <Descriptions.Item label="出版社">{book.publisher}</Descriptions.Item>
          <Descriptions.Item label="出版日期">{book.publish_date}</Descriptions.Item>
          <Descriptions.Item label="语言">{book.language}</Descriptions.Item>
          <Descriptions.Item label="页数">{book.page_count}</Descriptions.Item>
          <Descriptions.Item label="分类">{book.category?.name || '-'}</Descriptions.Item>
          <Descriptions.Item label="封面图片">
            {book.cover_image ? (
              <img 
                src={book.cover_image} 
                alt="封面" 
                style={{ maxWidth: 100, maxHeight: 150 }}
              />
            ) : (
              '无'
            )}
          </Descriptions.Item>
          <Descriptions.Item label="描述" span={2}>
            {book.description || '无'}
          </Descriptions.Item>
        </Descriptions>
      </Card>

      {borrowing && (
        <Card title="借阅信息" style={{ marginTop: 16 }}>
          <Descriptions bordered column={2}>
            <Descriptions.Item label="借阅人">{borrowing.user?.username || '-'}</Descriptions.Item>
            <Descriptions.Item label="借阅时间">{borrowing.borrow_date}</Descriptions.Item>
            <Descriptions.Item label="应还时间">{borrowing.due_date}</Descriptions.Item>
            <Descriptions.Item label="实际归还时间">
              {borrowing.return_date || '未归还'}
            </Descriptions.Item>
            <Descriptions.Item label="借阅状态">
              {borrowing.status === 'borrowed' ? '借阅中' : '已归还'}
            </Descriptions.Item>
            <Descriptions.Item label="备注">
              {borrowing.notes || '无'}
            </Descriptions.Item>
          </Descriptions>
        </Card>
      )}
    </div>
  );
};

export default BookDetail;
